﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Cofe.Core;
using Cofe.Web.Models;

namespace Cofe.Web.Controllers
{
    public class ExplorerController : Controller
    {
        //
        // GET: /Explore/
        public ActionResult Index()
        {
            return View();
        }

        private IEnumerable<LinkViewModel> generateBreadcrumb(string path)
        {
            //yield return LinkViewModel.CreateNew("Home", "Home", "Index", null);
            yield return LinkViewModel.CreateNew("Root", "Explorer", "Browse", null);

            if (!(String.IsNullOrEmpty(path)))
            {
                string cur = "";
                foreach (var s in path.Split('\\'))
                {
                    cur = PathFE.Combine(cur, s);
                    yield return LinkViewModel.CreateNew(s, "Explorer", "Browse", new { path = cur });
                }
            }
        }

        //
        // GET: /Explore/List
        public async Task<ActionResult> Browse(string path = "")
        {            
            var foundDir = await EntryFE.TryParsePathAsync<ICofeDirectoryInfo>(path);
            if (foundDir == null)
                return HttpNotFound();            

            ViewBag.Path = path;
            ViewBag.Breadcrumb = generateBreadcrumb(path).ToList();
            ViewBag.IconPath = Url.RouteUrl("DefaultApi", new
                {
                    httproute = "",
                    controller = "entry",
                    id = foundDir.EntryTypeInfo.Id,
                    resource = "largeIcon"
                });

            return View(ExplorerViewModel.FromDirectory(foundDir));
        }

        //public async Task<ActionResult> _Hierarchy(string path = "")
        //{
        //    var foundDir = await EntryFE.TryParsePathAsync<ICofeDirectoryInfo>(path);
        //    if (foundDir == null)
        //        return HttpNotFound();

        //    List<ExplorerViewModel> retModels = new List<ExplorerViewModel>();                
        //    var current = foundDir;

        //    while (current != null)
        //    {
        //        retModels.Add(ExplorerViewModel.FromDirectory(current, false, false));
        //        current = current.Parent;
        //    }


        //    retModels.Reverse();
        //    return PartialView(retModels);
        //}
    }
}
